package com.esiag.isidis.fi.pdsteam.service;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
import java.util.Properties;

import com.dao.MessageDAO;
import com.dao.SourceDAO;
import com.dao.impl.MessageDAOImpl;
import com.dao.impl.SourceDAOImpl;
import com.esiag.isidis.fi.pdsteam.entity.ParsedMessage;
import com.esiag.isidis.fi.pdsteam.entity.RawByteObject;
import com.rev.Message;
import com.rev.Source;

public class ObserverReceiver implements Observer {

	public void update(Observable arg0, Object object) {
		try {
			Properties properties = new Properties();
			FileInputStream file = new FileInputStream(
					"C:\\Users\\DAOUDA\\Documents\\config.properties");
			properties.load(file);
			String pathFileConfig = properties.getProperty("pathFileConfig");
			file.close();
			RawByteObject rawByteObject = new RawByteObject((byte[]) object);
			doWork(rawByteObject, pathFileConfig);
		} catch (FileNotFoundException e) {
			System.out.println("File not found");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void doWork(RawByteObject rawByteObject, String pathFileConfig) {
		try {
			// parse data
			IParser dataParser = new DataParser();
			ParsedMessage parsedMessage = dataParser.parse(rawByteObject,
					pathFileConfig);
			SourceDAO sourceDAO = new SourceDAOImpl();
			Source source = sourceDAO.findById((Integer) parsedMessage
					.get("idSource"));
			MessageDAO messageDAO = new MessageDAOImpl();
			Message message = messageDAO.findById((Integer) parsedMessage
					.get("idMessage"));
			// dispatch message
			MessageDispatcher dispatcher = new MessageDispatcher();
			if (message == null)
				System.out.println("No message has this idMessage: "
						+ parsedMessage.get("idMessage") + " in database");
			if (source == null)
				System.out.println("No Souce has this idSource: "
						+ parsedMessage.get("idSource") + " in database");
			dispatcher.dispatche(message, source);
		} catch (Exception e) {
			System.out.println("Exception in doWork");
		}
	}
}
